<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            @clear="getUserList"
            clearable
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="AddDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-table :data="userList" border stripe>
            <!--            <el-table-column label="#" type="index"> </el-table-column>-->
            <el-table-column label="#" prop="id" sortable sort-by="id"> </el-table-column>
            <el-table-column label="姓名" prop="username" sortable> </el-table-column>
            <el-table-column label="邮箱" prop="email"> </el-table-column>
            <el-table-column label="电话" prop="mobile"> </el-table-column>
            <el-table-column label="角色" prop="role_name"> </el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.mg_state"
                  @change="userStateChanged(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180px">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="success"
                  size="small"
                  @click="showEditDialog(scope.row)"
                  icon="el-icon-edit"
                >
                </el-button>
                <!-- 分配角色 -->
                <el-tooltip
                  content="分配角色"
                  placement="top"
                  :enterable="false"
                  effect="dark"
                >
                  <!-- content to trigger tooltip here -->
                  <el-button type="primary" size="small" @click="setRole(scope.row)" icon="el-icon-setting">
                  </el-button>
                </el-tooltip>
                <!-- 删除 -->
                <el-button type="danger" :disabled="scope.row.username=='admin'?true:false" @click="RemoveUserById(scope.row.id)" size="small" icon="el-icon-delete">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页-->
          <div class="block">
            <!-- <span class="demonstration">完整功能</span> -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryInfo.pagenum"
              :page-sizes="[1, 2, 5, 10]"
              :page-size="5"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <!--添加用户的对话框-->
    <el-dialog
      title="添加用户"
      modal
      :visible.sync="AddDialogVisible"
      @close="addDialogClosed"
      width="50%"
    >
      <!--内容主体区域-->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框-->
    <el-dialog
      :title="'修改用户：'+editForm.username "
      modal
      :visible.sync="EditDialogVisible"
      @close="editDialogClosed"
      width="50%"
    >
      <!--内容主体区域-->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" >
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditUser">确 定</el-button>
      </span>
    </el-dialog>

    <!--    分配角色的对话框-->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%">
      <div>
        <p>当前用户：{{ userInfo.username }}</p>
        <p>当前角色： {{ userInfo.role_name}}</p>
        <p>更改角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRoleForUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getUserList()
  },
  data: function() {
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
      if (regEmail.test(value)) return cb()
      cb(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(\+86)?1[3456789]\d{9}$/
      if (regMobile.test(value)) return cb()
      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      AddDialogVisible: false,
      EditDialogVisible: false,
      setRoleDialogVisible: false,
      // 被选中的角色id
      selectRoleId: '',
      userInfo: {},
      roleList: [],
      // 添加用户的表单数据
      addForm: {
        username: 'kevin',
        password: 'bianque007',
        mobile: '13735528225',
        email: 'zhanggai_ok@126.com'
      },
      editForm: {},
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // {
          //   type: 'email',
          //   message: '请输入正确的邮箱地址',
          //   trigger: ['blur', 'change']
          // },
          { trigger: 'blur', validator: checkEmail }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        this.$message(res.meta.msg)
        return this.$message.error('数据获取失败')
      }
      // this.$message(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
      console.log(this.userList)
    },
    handleSizeChange(newsize) {
      // console.log(newsize)
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    handleCurrentChange(newpage) {
      // console.log(newpage)
      this.queryInfo.pagenum = newpage
      this.getUserList()
    },
    // 监听Switch 开关状态改变
    async userStateChanged(UserInfo) {
      // console.log(UserInfo)
      const { data: res } = await this.$http.put(
        `users/${UserInfo.id}/state/${UserInfo.mg_state}`
      )
      //  `users/${UserInfo.id}/state/${UserInfo.mg_state}`
      if (res.meta.status !== 200) {
        UserInfo.mg_state = !UserInfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    AddUser: function() {
      this.$refs.addFormRef.validate(async valid => {
        console.log(this.$refs.addFormRef)
        console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.AddDialogVisible = false
        this.getUserList()
      })
    },
    EditUser: function() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`, this.editForm)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.EditDialogVisible = false
        this.getUserList()
      })
    },
    showEditDialog: async function(scope) {
      this.EditDialogVisible = true
      const { data: res } = await this.$http.get(
        `users/${scope.id}`,
        this.addForm
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editForm = res.data
      // console.log(this.editForm)
      // this.$message.success('修改')
    },
    //  根据uid删除用户
    RemoveUserById: function(uid) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`users/${uid}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 展示分配角色的对话框
    setRole: async function(userInfo) {
      // console.log(userInfo)
      this.selectRoleId = null
      this.userInfo = userInfo
      // 在展示对话框之前获取多有角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roleList = res.data
      this.setRoleDialogVisible = true
      // console.log(res.data)
    },
    // 更新用户角色
    updateRoleForUser: async function() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`,
        { rid: this.selectRoleId })
      if (res.meta.status !== 200) { return this.$message.error(res.meta.msg) }
      this.$message.success(res.meta.msg)
      // this.$message.info(this.selectRoleId.toString())
      this.setRoleDialogVisible = false
      this.getUserList()
    }

  }
}
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.block {
  margin-top: 15px;
}
</style>
